%% calibration of spread

clear;
clc;




S_all=[55.15
16.58
13.05
11.87
11.18
10.82
10.43
10.49
11.16
11.18
10.68
10.64
10.36
29.92];

S_all=S_all/100;


S_data=S_all;

T_spread=length(S_data);



V_all2=[14.98
10.15
9.11
8.62
7.84
7.33
7.18
6.52
6.14
6.00
5.60
5.58
5.34
5.30
5.23
5.04
5.06
4.99
5.20
5.34
5.32
5.39
5.81
6.36
7.17
11.62];

V_all2=V_all2/100;



len=length(V_all2);

V_nas=zeros(len/2,1);

for t=1:len/2
    V_nas(t)=V_all2(2*t-1)+V_all2(2*t);
end

V_data=V_nas;


T_vol=length(V_data);






x0=[0.2349    0.0949  113.8589   14.8091    5.2757   49.7382]; % N_M=1  N_I=1.5  tau_V=1 theta_bar=1 lambda_U=1
% Result: [alpha_0, alpha, beta, beta_T,  tau_V, lambda_I,  N_U]=[ 0.2383    0.0955  111.2577   15.4111    5.3727  283.4798]







F=@(x)sum((mySpread(T_spread, x(1), x(2), x(3), x(4), x(5), x(6))-S_data([1,3,5,7,9,11,13,14])).^2)...
    +sum((myVol(T_vol, x(1), x(2), x(3), x(4), x(5), x(6))-V_data([1,3,5,7,9,11,13])).^2);



[xfunc, fval]= fminsearch(F, x0)



S_fit=mySpread(T_spread, xfunc(1), xfunc(2), xfunc(3), xfunc(4), xfunc(5), xfunc(6));



ts=0:1/(T_spread-1):1;

figure(1)
plot(ts, S_data, 'o', ts([1,3,5,7,9,11,13,14]), S_fit);
colororder(["r"; "#0072BD"])
legend('Emprical Average', 'Model Calibration','interpreter','latex')
xlabel('$t/T$','interpreter','latex')
ylabel('Expected Bid-Ask Spread', 'interpreter','latex')
ylim([0 0.6])


tv=1/T_vol:1/T_vol:1;

V_fit=myVol(T_vol, xfunc(1), xfunc(2), xfunc(3), xfunc(4), xfunc(5), xfunc(6));

figure(2)
plot(tv, V_data, 'o', tv([1,3,5,7,9,11,13]), V_fit);
colororder(["r"; "#0072BD"])
legend('Emprical Average', 'Model Calibration','interpreter','latex')
xlabel('$t/T$','interpreter','latex')
ylabel('Expected Turnover', 'interpreter','latex')
ylim([0.05 0.35])






